/*
 * Copyright (c)  2008 Sebastien Tremblay
 *
 * id3-tag-builder - threads.WorkerPool.java
 *
 * All source and documentation is copyrighted by Sebastien Tremblay
 * (seb at ryders dot net) and made available under the Apache License 2.0.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id: WorkerPool.java 33 2010-04-02 07:47:55Z ryders $
 */
package com.empireone.id3tagbuilder.threads;

import com.empireone.id3tagbuilder.classes.Format;
import com.empireone.id3tagbuilder.classes.Path;
import com.empireone.id3tagbuilder.classes.db.MusicDb;
import com.empireone.id3tagbuilder.classes.db.MusicDbException;
import com.empireone.id3tagbuilder.classes.db.SqliteMusicDb;
import com.empireone.id3tagbuilder.classes.db.XmlMusicDb;
import com.empireone.id3tagbuilder.helpers.FileHelper;
import com.empireone.id3tagbuilder.helpers.StringHelper;
import com.empireone.id3tagbuilder.settings.ApplicationSettings;
import com.empireone.id3tagbuilder.threads.StatusUpdateListener.MsgType;
import java.io.File;
import java.util.ResourceBundle;
import java.util.Vector;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * The <code>WorkerPool</code> is the handle to the multiple threads (see
 * <see>TagBuilder</see>) used by the application to process tasks.
 *
 * @author Sebastien Tremblay
 */
public class WorkerPool extends Thread {

    private ThreadPoolExecutor tpe;
    private int THREAD_POOL_SIZE = 1;
    private ApplicationSettings settings;
    private MusicDb musicDb;
    private Format format;
    private Vector<Path> albums;
    private StatusUpdateListener caller;
    private ResourceBundle messages;

    /** Creates a new instance of WorkerPool
     * @param caller
     * @param settings
     * @param format
     * @param albums
     * @param musicDb
     */
    public WorkerPool(StatusUpdateListener caller, ApplicationSettings settings, Format format, Vector<Path> paths) {
        this.settings = settings;
        this.format = format;
        this.albums = getAlbumsFromPaths(paths);
        this.caller = caller;
         if (settings.getMaintainMusicDb()) {
            if (settings.getMusicDbType().equalsIgnoreCase("sqlite")) {
                musicDb = new SqliteMusicDb();
            } else {
                musicDb = new XmlMusicDb();
            }
            musicDb.setVersion(settings.getVersion());
            musicDb.setUri(settings.getMusicDbUri());
            try {
                musicDb.initialise();
            } catch (MusicDbException ex) {
                caller.status(MsgType.ERROR, StringHelper.substitute(getString("db-init-failure"),ex.getMessage()));
                musicDb = null;
            }
        }
    }

    private Vector<Path> getAlbumsFromPaths(Vector<Path> paths) {
        Vector<Path> res = new Vector<Path>();
        for (Path p : paths) {
            if (p.getDepth() == 0) {
                res.add(p);
            } else {
                for (Path c : p.getChildren()) {
                    Vector<Path> children = new Vector<Path>();
                    children.add(c);
                    res.addAll(getAlbumsFromPaths(children));
                }
            }
        }
        return res;
    }

    /**
     *
     */
    @Override
    public void run() {

        caller.status(MsgType.STARTED, StringHelper.substitute(getString("process-started"), THREAD_POOL_SIZE + "|" + albums.size()));

        tpe = new ThreadPoolExecutor(
                THREAD_POOL_SIZE,
                THREAD_POOL_SIZE * 2,
                50000L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());

        caller.updateWorkload(albums.size());

        for (Path album : albums) {

            Vector<File> files = FileHelper.getFilesByExt(album.getUri(), ".mp3");

            caller.updateWorkload(files.size());

            Runnable run = new TagBuilder(album, files, format, settings, caller, musicDb);

            caller.status(MsgType.JOB_CREATED, StringHelper.substitute(getString("job-created"), "|" + album.getName() + "|" + files.size()));

            tpe.execute(run);
        }

        caller.status(MsgType.SCHEDULED);

        tpe.shutdown();
    }

    /**
     *
     * @param key
     * @return
     */
    protected String getString(String key) {
        if (messages == null) {
            messages = ResourceBundle.getBundle("com.empireone.id3tagbuilder.Messages", settings.getLocale());
        }
        return messages.getString(key);
    }

    /**
     *
     */
    public void halt() {
        if (tpe != null) {
            tpe.shutdownNow();
            musicDb.terminate();
        }
        caller.status(MsgType.HALTED, getString("user-halted"));
    }

    /**
     * 
     */
    public void reset() {
        musicDb.terminate();
    }
}
